from fastapi import FastAPI, Path, Request, Query
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
import os

from data1_analysis import analyze_weather1
from data14_analysis import analyze_weather14
from weather import get_weather_data, CITY_CODES

app = FastAPI(title='天气预报数据分析系统', description='提供天气数据分析和可视化')

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 设置模板目录
templates = Jinja2Templates(directory="templates")

@app.get(path='/', response_class=HTMLResponse)
async def index(request: Request):
    """主页"""
    return templates.TemplateResponse("index.html", {"request": request, "cities": CITY_CODES})


@app.get("/weather1", response_class=HTMLResponse)
async def weather1_analysis(request: Request, city: str = None):
    """24小时天气数据分析页面"""
    # 如果有城市参数，先获取该城市的天气数据
    if city and city in CITY_CODES:
        weather_data = get_weather_data(city_name=city)
        weather1_data = weather_data['weather1_data']
    else:
        # 默认使用石家庄
        weather_data = get_weather_data()
        weather1_data = weather_data['weather1_data']
    
    results = analyze_weather1(weather1_data)
    if "error" in results:
        return templates.TemplateResponse(
            "error.html", 
            {
                "request": request,
                "error_message": results["error"]
            }
        )
    
    return templates.TemplateResponse(
        "weather1.html", 
        {
            "request": request, 
            "chart_data": results,
            "city": city if city else "石家庄",
            "cities": CITY_CODES
        }
    )


@app.get("/weather14", response_class=HTMLResponse)
async def weather14_analysis(request: Request, city: str = None):
    """14天天气预报数据分析页面"""
    # 如果有城市参数，先获取该城市的天气数据
    if city and city in CITY_CODES:
        weather_data = get_weather_data(city_name=city)
        weather14_data = weather_data['weather14_data']
    else:
        # 默认使用石家庄
        weather_data = get_weather_data()
        weather14_data = weather_data['weather14_data']
    
    results = analyze_weather14(weather14_data)
    if "error" in results:
        return templates.TemplateResponse(
            "error.html", 
            {
                "request": request,
                "error_message": results["error"]
            }
        )
    
    return templates.TemplateResponse(
        "weather14.html", 
        {
            "request": request, 
            "chart_data": results,
            "city": city if city else "石家庄",
            "cities": CITY_CODES
        }
    )


@app.get("/api/weather1", response_class=JSONResponse)
async def api_weather1_analysis(city: str = None):
    """24小时天气数据分析API"""
    # 如果有城市参数，先获取该城市的天气数据
    if city and city in CITY_CODES:
        weather_data = get_weather_data(city_name=city)
        weather1_data = weather_data['weather1_data']
    else:
        # 默认使用石家庄
        weather_data = get_weather_data()
        weather1_data = weather_data['weather1_data']
    
    return analyze_weather1(weather1_data)


@app.get("/api/weather14", response_class=JSONResponse)
async def api_weather14_analysis(city: str = None):
    """14天天气预报数据分析API"""
    # 如果有城市参数，先获取该城市的天气数据
    if city and city in CITY_CODES:
        weather_data = get_weather_data(city_name=city)
        weather14_data = weather_data['weather14_data']
    else:
        # 默认使用石家庄
        weather_data = get_weather_data()
        weather14_data = weather_data['weather14_data']
    
    return analyze_weather14(weather14_data)


@app.get("/api/fetch_city_weather", response_class=JSONResponse)
async def fetch_city_weather(city: str = Query(..., description="城市名称")):
    """获取指定城市的天气数据并进行分析"""
    if city not in CITY_CODES:
        return {"error": f"不支持的城市: {city}，请选择有效的城市"}
    
    try:
        # 获取指定城市的天气数据
        weather_data = get_weather_data(city_name=city)
        
        # 分析数据
        weather1_data = analyze_weather1(weather_data['weather1_data'])
        weather14_data = analyze_weather14(weather_data['weather14_data'])
        
        return {
            "success": True,
            "city": city,
            "city_code": weather_data["city_code"],
            "message": f"成功获取{city}的天气数据并完成分析"
        }
    except Exception as e:
        return {
            "success": False,
            "city": city,
            "error": str(e),
            "message": f"获取{city}的天气数据失败: {str(e)}"
        }


@app.get("/api/cities", response_class=JSONResponse)
async def get_cities():
    """获取所有支持的城市列表"""
    return {
        "cities": [{"name": city, "code": code} for city, code in CITY_CODES.items()]
    }
